#include "StdAfx.h"
#include <gl/glut.h>
#include <cmath>
#include "model_factory.h"

model_factory* model_factory::ms_singleton;
model_factory::model_factory(void)
{
}

model_factory::~model_factory(void)
{
	ms_singleton = 0;
}

model_factory& model_factory::get_model_factory()
{
	if(ms_singleton == NULL)
	{
		ms_singleton = new model_factory();
	}
	return (*ms_singleton);
}

bool model_factory::load_model(string& filepath, string& name)
{
	if(model_map.find(name) != model_map.end())
	{
		error_code = ERROR_CODE_MODEL_EXISTED;
		return false;
	}
	GLMmodel* p_model = glmReadOBJ(filepath.c_str());
	if(p_model==NULL)
	{
		error_code = ERROR_CODE_FILE_NOT_FOUND;
		return false;
	}
	glmUnitize(p_model);
	model_map.insert(map<string,GLMmodel*>::value_type(name, p_model));
	return true;
}

bool model_factory::unload_model(string& name)
{
	if(model_map.find(name) == model_map.end())
	{
		error_code = ERROR_CODE_MODEL_NOT_EXIST;
		return false;
	}

	glmDelete(model_map[name]);
	model_map.erase(name);
	return true;
}

bool model_factory::draw_model(string name, vector3d& position, vector3d& rotation, vector3d& scale,
	unsigned int draw_mode)
{
	if(model_map.find(name)==model_map.end())
	{
		error_code = ERROR_CODE_MODEL_NOT_EXIST;
		return false;
	}

	glPushMatrix();
	glTranslatef(position.x(), position.y(), position.z());

	vector3d z(0.0f,0.0f,1.0f);
	vector3d axis = z.cross(rotation);
	axis.normalize();
	float angle = (float)acos(rotation.z()/rotation.len());

	glRotatef(angle*180/3.1415f, axis.x(), axis.y(), axis.z());

	glScalef(scale.x(), scale.y(), scale.z());
	glmDraw(model_map[name], draw_mode);
	glPopMatrix();
	return true;
}